import React, { useEffect, useRef, useState } from "react";

const useLazyLoadImg = (
  src: string
): [React.ReactNode, React.Dispatch<string>] => {
  const [localSrc, setLocalSrc] = useState("");
  const imgRef = useRef();

  useEffect(() => {
    const ob = new IntersectionObserver((arr) => {
      if (arr[0].isIntersecting) {
        setLocalSrc(src);
        ob.disconnect();
      }
    });
    ob.observe(imgRef.current);
  }, []);

  return [
    <div ref={imgRef}>
      {localSrc ? (
        <img style={{ height: "100px", width: "100px" }} src={localSrc} />
      ) : (
        <div style={{ height: "100px", width: "100px" }}>loading</div>
      )}
    </div>,
    setLocalSrc,
  ];
};

export default useLazyLoadImg;
